﻿using StudentInfoSystem.UI.Views;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;

namespace StudentInfoSystem.UI.Services
{
    public class StartupTaskManager
    {
        private readonly SplashScreenWindow _splashScreen;
        private readonly Action _mainWindowInitializer;
        private readonly Action _postLoadActions;
        private Bootstrapper? _bootstrapper;
        private  DateTime _startTime;

        public StartupTaskManager(
            SplashScreenWindow splashScreen,
            Action mainWindowInitializer,
            Action postLoadActions)
        {
            _splashScreen = splashScreen;
            _mainWindowInitializer = mainWindowInitializer;
            _postLoadActions = postLoadActions;
        }

        public async Task StartAsync()
        {
            // 创建动画完成信号
            var cardAnimationTask = new TaskCompletionSource<bool>();

            // 订阅动画完成事件
            _splashScreen.CardAnimationCompleted += () => cardAnimationTask.TrySetResult(true);

            // 2. 启动粒子动画（UI线程）
            Application.Current.Dispatcher.Invoke(() => _splashScreen.StartParticleConvergence());

            await Task.Delay(800);

            // 立即启动卡片动画
            Application.Current.Dispatcher.Invoke(() => _splashScreen.StartCardFormation());

            await cardAnimationTask.Task;

            // 阶段2: 并行执行后台任务和等待卡片动画
            await ExecuteBackgroundTask(20, "启动模块...", () => {
                // 在后台线程执行耗时操作
                _startTime = DateTime.Now;
                _bootstrapper = new Bootstrapper();
                _bootstrapper.Start();
            });


            // 阶段3: 更新进度（主线程操作）
            // 阶段3: 并行执行资源加载和平滑进度更新
            await ExecuteResourceLoadingWithSmoothProgress();

            // 阶段4: 主窗口初始化（增加中间进度）
            await ExecuteUiTask(80, "准备主界面...", () =>
            {
                _mainWindowInitializer();
                // 增加中间进度点
            });

            // 阶段4: 确保最小显示时间（增加进度动画）
            var elapsed = DateTime.Now - _startTime;
            var minDisplayTime = TimeSpan.FromSeconds(3);
            var remaining = minDisplayTime - elapsed;
            if (remaining > TimeSpan.Zero)
            {
                for (int i = 90; i <= 99; i += 1)
                {
                    await UpdateProgressAsync(i, $"启动中...");
                    await Task.Delay(40); // 直接等待，无需Task.WhenAll
                }
            }

            await UpdateProgressAsync(100, "启动完成");
            await Task.Delay(200);
            await Application.Current.Dispatcher.InvokeAsync(() => {
                _postLoadActions?.Invoke();
            });
        }

        public void Stop()
        {
            _bootstrapper?.Stop();
        }


        // 辅助方法：后台线程执行
        private async Task ExecuteBackgroundTask(int progress, string message, Action action)
        {
            // UI更新仍在主线程
            await UpdateProgressAsync(progress, message);
            // 耗时操作移出UI线程
            await Task.Run(action);
        }

        // 辅助方法：UI线程执行
        private async Task ExecuteUiTask(int progress, string message, Action action)
        {
            // 确保进度更新可见
            await UpdateProgressAsync(progress, message);

            // 执行UI操作并确保完成
            await Application.Current.Dispatcher.InvokeAsync(action);

            // 增加视觉停留时间
            await Task.Delay(100);
        }




        private async Task ExecuteResourceLoadingWithSmoothProgress()
        {
            // 更新初始状态
            await UpdateProgressAsync(25, "加载资源...");

            // 创建资源加载任务
            var resourceTask = Task.Run(() => ThemeService.PreloadResources());

            // 创建进度动画任务
            var progressTask = SmoothProgressTo(80, 1900, "加载资源...");

            // 等待两者都完成
            await Task.WhenAll(resourceTask, progressTask);
        }

        private async Task SmoothProgressTo(int targetProgress, int durationMs, string message)
        {
            // 使用简单的循环逐步增加进度
            int startProgress = 40; // 我们从这个进度开始
            int steps = targetProgress - startProgress;
            int delayPerStep = durationMs / steps;
            delayPerStep = Math.Max(10, Math.Min(100, delayPerStep)); // 限制在10-100ms

            for (int i = 0; i < steps; i++)
            {
                int newProgress = startProgress + i;
                await UpdateProgressAsync(newProgress, message);
                await Task.Delay(delayPerStep);
            }

            // 确保最终到达目标值
            await UpdateProgressAsync(targetProgress, message);
        }

        private async Task UpdateProgressAsync(int progress, string message)
        {
            await Application.Current.Dispatcher.InvokeAsync(() =>
            {
                try
                {
                    // 直接调用现有的UpdateProgress方法
                    _splashScreen.UpdateProgress(progress, message);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"进度更新失败: {ex.Message}");
                }
            });
        }

    }
}